const app = getApp()
const mockData = require('../../utils/data.js')

Page({
  data: {
    cartItems: [],
    selectedItems: [],
    allSelected: false,
    totalPrice: 0
  },
  
  onLoad() {
    this.loadCart()
  },
  
  onShow() {
    this.loadCart()
  },
  
  loadCart() {
    const cart = app.globalData.cart || []
    
    // 合并产品信息
    const cartItems = cart.map(item => {
      const product = mockData.products.find(p => p.id === item.id) || mockData.products[0]
      return {
        ...item,
        ...product,
        expired: this.checkExpired(item.date),
        offShelf: false
      }
    })
    
    const selectedItems = cartItems.filter(item => item.selected)
    const allSelected = cartItems.length > 0 && selectedItems.length === cartItems.length
    
    this.setData({
      cartItems,
      selectedItems,
      allSelected,
      totalPrice: this.calculateTotal(selectedItems)
    })
  },
  
  checkExpired(date) {
    if (!date) return false
    const today = new Date()
    const travelDate = new Date(date)
    return travelDate < today
  },
  
  calculateTotal(items) {
    return items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  },
  
  toggleSelectAll() {
    const allSelected = !this.data.allSelected
    const cartItems = this.data.cartItems.map(item => ({
      ...item,
      selected: allSelected && !item.expired && !item.offShelf
    }))
    
    const selectedItems = cartItems.filter(item => item.selected)
    
    this.setData({
      cartItems,
      allSelected,
      selectedItems,
      totalPrice: this.calculateTotal(selectedItems)
    })
    
    this.updateCart(cartItems)
  },
  
  toggleSelect(e) {
    const index = e.currentTarget.dataset.index
    const cartItems = this.data.cartItems
    cartItems[index].selected = !cartItems[index].selected
    
    const selectedItems = cartItems.filter(item => item.selected)
    const allSelected = cartItems.length > 0 && selectedItems.length === cartItems.length
    
    this.setData({
      cartItems,
      selectedItems,
      allSelected,
      totalPrice: this.calculateTotal(selectedItems)
    })
    
    this.updateCart(cartItems)
  },
  
  updateCart(cartItems) {
    app.globalData.cart = cartItems.map(item => ({
      id: item.id,
      date: item.date,
      quantity: item.quantity,
      selected: item.selected
    }))
    wx.setStorageSync('cart', app.globalData.cart)
  },
  
  deleteItem(e) {
    const index = e.currentTarget.dataset.index
    wx.showModal({
      title: '提示',
      content: '确定要删除这个商品吗？',
      success: (res) => {
        if (res.confirm) {
          const cartItems = this.data.cartItems
          cartItems.splice(index, 1)
          
          const selectedItems = cartItems.filter(item => item.selected)
          const allSelected = cartItems.length > 0 && selectedItems.length === cartItems.length
          
          this.setData({
            cartItems,
            selectedItems,
            allSelected,
            totalPrice: this.calculateTotal(selectedItems)
          })
          
          this.updateCart(cartItems)
        }
      }
    })
  },
  
  editItem(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.cartItems[index]
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${item.id}`
    })
  },
  
  clearCart() {
    wx.showModal({
      title: '提示',
      content: '确定要清空购物车吗？',
      success: (res) => {
        if (res.confirm) {
          app.globalData.cart = []
          wx.setStorageSync('cart', [])
          this.setData({
            cartItems: [],
            selectedItems: [],
            allSelected: false,
            totalPrice: 0
          })
        }
      }
    })
  },
  
  goToCheckout() {
    if (this.data.selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: '/pages/checkout/checkout'
    })
  }
})

